package activity

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	error2 "OnlineRetailers/models/errorDeal"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
)

type PostActivity struct {
	beego.Controller
}

func (c *PostActivity) PostActivity() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/activity/PostActivity"
	var err error

	activity := &Admin.Activity{}
	log := &error2.Log{}
	mes := &error2.Mes{}

	o := orm.NewOrm()

	fmt.Println(c.GetString("activity"))
	err = json.Unmarshal([]byte(c.GetString("activity")), activity)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	s := strconv.FormatInt(time.Now().Unix(), 10)
	activity.ActivityId = "ACT" + s

	err = session2.CheckSession(c.Ctx.Request.Header["Session"], 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	if len(activity.Classification) != 0 {
		err = PostClassM2M(o, activity)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "402", err, addr, err.Error())
			return
		}
	}

	//fmt.Println(key)

	_, err = o.Insert(activity)

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "402", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}

func PostClassM2M(o orm.Ormer, activity *Admin.Activity) (err error) {
	m2m := o.QueryM2M(activity, "Classification")
	_, err = m2m.Add(activity.Classification)
	return err
}
